package org.codeblue.support.exceptions;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.codeblue.support.beans.DefaultResp;
import org.codeblue.support.constantes.SystemConstantes;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
/**
 * 所有异常转换为JSON串返回给客户端.
 * @author jiulong.hu
 *
 */
public class MySimpleMappingExceptionResolver extends
		SimpleMappingExceptionResolver {//HandlerExceptionResolver
	private Logger log = Logger.getLogger(MySimpleMappingExceptionResolver.class);

	protected org.springframework.web.servlet.ModelAndView doResolveException(//HandlerExceptionResolver
			javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response, Object obj,
			Exception e) {
		log.error("系统内部异常", e);
	//	log.error(e,e.getCause().fillInStackTrace());
	     printExpJson(response, e);
		return null;
	}



	public   void printExpJson(HttpServletResponse response, Exception e) {
		PrintWriter out;
		try {
			out = response.getWriter();
			response.addHeader("Content-Type", "application/json;charset=UTF-8");
			DefaultResp<String> dr = new DefaultResp<String>(false,SystemConstantes.ERROR_MSG);

			if (e.getCause() instanceof BusinessException||e instanceof BusinessException) {
				Throwable ee = e.getCause();
				ee = ee==null?e:ee;
				try {
					dr.setMsg(BeanUtils.getProperty(ee, "customMsg"));
				} catch (IllegalAccessException e1) {
					log.warn(e1.getMessage());
				} catch (InvocationTargetException e1) {
					log.warn(e1.getMessage());
				} catch (NoSuchMethodException e1) {
					log.warn(e1.getMessage());
				}
			}else {
				dr.setMsg("系统内部异常");
				dr.setData(null);
			}

			if(log.isInfoEnabled()&&e!=null) {
				log.info(e.getMessage());
			}

			final ObjectMapper objMapper = new ObjectMapper();
			out.write(objMapper.writeValueAsString(dr));
			out.flush();
			out.close();
		} catch (IOException e1) {
			log.warn("该异常不做处理", e1);
		}
	}
}
